<?php
/*
 * Created on Feb 21, 2009
 * FileName: AjaxController.php
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
	
class Place_AjaxController extends Clu_Controller_Action_Hvn
{
	public function init()
	{
		//require_once (APP_PATH.'/modules/article/Model/Article.php');
		//require_once (APP_PATH.'/modules/category/Model/Category.php');
		
		$this->m = new place_Model_Place();
		$this->mArticle = new article_Model_Service();
		$this->mDistrict = new place_Model_District();
		$this->mVillage = new place_Model_Village();
		$this->mCategory = new category_Model_Category();
		$this->mCategory->setTables('place');
		parent::init();
	}
	
	
	public function getDistrictAction()
    {	
    	$city_id = $this->_request->getParam('city_id');
		if ($this->_request->isXmlHttpRequest())
		{
		    $ret = array();
		    //If no city selected then return only "no district" option
		    if ($city_id == 0)
			{
				$ret[] =  array('id' => 0,
					 		    'name' => t(718));
			}
			else
			{
				$ret[] =  array('id' => 0,
					 		    'name' => t(719));
				$districts = $this->mDistrict->getDistricts($city_id);
				function cmp($a, $b)
				{
				   return strcmp($a['district_name'], $b['district_name']);
				}
				usort($districts, "cmp");
				foreach($districts as $d)
				{
					if($d['city_id'] == $city_id)
						$ret[] =  array(
	                           		 'id' => $d['district_id'],
							 		 'name' => $d['district_name']
	                   			);
				}
			}
			
			$this->_helper->json->sendJson($ret);
		}
    }
    
    public function getVillageAction()
    {	
    	$district_id = $this->_request->getParam('district_id');
    	
		if ($this->_request->isXmlHttpRequest())
		{
		    $ret = array();
		    if ($district_id == 0)
			{
				$ret[] =  array('id' => 0,
					 		    'name' => t(720));
			}
			else
			{
				$ret[] =  array('id' => 0,
					 		    'name' => t(721));
				$villages = $this->mVillage->getVillages($district_id);
				function cmp($a, $b)
				{
				   return strcmp($a['village_name'], $b['village_name']);
				}
				usort($villages, "cmp");
				foreach($villages as $d)
				{
					if($d['district_id'] == $district_id)
						$ret[] =  array(
	                           		 'id' => $d['village_id'],
							 		 'name' => $d['village_name']
	                   			);
				}
			}
			$this->_helper->json->sendJson($ret);
		}
    }
    
    
    public function getRootTypeAction()
    {	
    	$rtype = $this->_request->getParam('category');
		if ($this->_request->isXmlHttpRequest())
		{
		    $ret = array();
			$categories = $this->mCategory->getTree($rtype, 0, 1);
			function cmp($a, $b)
			{
		   		return strcmp($a['name'], $b['name']);
			}
			usort($categories, "cmp");
			foreach($categories as $c)
			{
				if($c['id'] == $rtype || $c['id'] == 1)
				{
					$c['id'] = 0;
					$c['displayName'] = t(112);
				}
				$ret[] =  array(
                       		 'id' => $c['id'],
//					 		 'name' => p($c['displayName'])
								'name' => $c['displayName']
               			);
			}
		}
		$this->_helper->json->sendJson($ret);
			
    }      
    
    public function getTypeAction()
    {	
    	$rtype = $this->_request->getParam('rtype');
		if ($this->_request->isXmlHttpRequest())
		{
			$ret = array();
			$categories = $this->mCategory->getTree($rtype, 1, 2);
			foreach($categories as $c)
			{
				$ret[] =  array(
							 'pid' => $c['pid'],
                       		 'id' => $c['id'],
					 		 'name' => p($c['name']),
//							'name' => $c['name'],
					 		 'tree_path' => $c['tree_path'],
					 		 'checked' => true | false
               			);
			}
			
		}
		$this->_helper->json->sendJson($ret);
    }      
    
    public function deletePlaceAction()
	{
		$sess = new Zend_Session_Namespace(CLU_NS);
		$id = $this->_request->getParam('id'); 
		if ($this->_request->isXmlHttpRequest())
		{
			$ret = array();
			//check permission
		    if (strpos ($sess->userPermissions, 'administer user') === false)
			{
				$ret['success'] = false;
				$ret['message'] = t(414);
				$this->_helper->json->sendJson($ret);
				exit();
			}
			
            if ($this->m->deleteByPrimary ($id) === false)
            {
            	$ret['success'] = false;
            }
            else
            	$ret['success'] = true;

			$this->_helper->json->sendJson($ret);
		}
	}	
	
	
	public function bulkPlaceAction()
    {   
    	$sess = new Zend_Session_Namespace(CLU_NS);
        if($this->_request->isXmlHttpRequest())
        {
	    	$places = $this->_request->getParam('places');
        	$ret = array();
        	//check permission
		    if (strpos ($sess->userPermissions, 'administer user') === false)
			{
				$ret['success'] = false;
				$ret['message'] = t(414);
				$this->_helper->json->sendJson($ret);
				exit();
			}
			
	        if (count($places) > 0)
	        {
	            $action = $this->_request->getParam('bulkaction');
		        if ($action === 'delete')
		        {
		        	if( $this->m->deleteListByPrimary($places))
	            		$ret['success'] = true;
		        }
		        else if($action === 'status')
		        {
	                $ret['status'] = $this->_request->getParam('changestatus');
	                if($this->m->bulkUpdateStatus($places, $ret))
	                	$ret['success'] = true;
		        }
	        }
	        else
	            $ret['success'] = false;
	        $ret['ids'] = $places;
	        $ret['bulkaction'] = $action;
	        $this->_helper->json->sendJson($ret);
        }
    }
    
    public function statusDeletedAction()
    {
    	$placeId = $this->_request->getParam('id');
    	if($this->_request->isXmlHttpRequest())
    	{
    		$ret = array();
    		//check permission
		    if (strpos ($sess->userPermissions, 'administer user') === false)
			{
				$ret['success'] = false;
				$ret['message'] = t(414);
				$this->_helper->json->sendJson($ret);
				exit();
			}
			
    		$ret['status'] = 'deleted';
    		if($this->m->bulkUpdateStatus((array)$placeId, $ret))
	        	$ret['success'] = true;
	    	$this->_helper->json->sendJson($ret);
    	}
    }
    
	public function ratePlaceAction()
	{
		$rating = $this->_request->getParam('rating');
		$ret = array();
		if ($this->_request->isXmlHttpRequest())
		{
			//TODO:
			$id = $this->_request->getParam('id');
			if (!$p = $this->m->findByPrimary($id))
			{
				$ret['success'] = false;
				$this->_helper->json->sendJson($ret);
				return;
			}
		
			$db = $this->db;
			$updateSql = "UPDATE places SET rating = rating + 1, rating_count = rating_count + ".$db->quote($rating, 'INTEGER')." WHERE id = ".$db->quote($id, 'INTEGER');
			try 
			{
    			$result = $db->query($updateSql);
			}
			catch (Exception $e)
			{
				$ret['success'] = false;
				$this->_helper->json->sendJson($ret);
				return;
			}
			$auth = Zend_Auth::getInstance();
    		$updateRate = "INSERT INTO ratings (rater_id, content_id) VALUES (".$auth->getIdentity()->id.", " .$db->quote($id, 'INTEGER'). ")";
    		$insertRate = $db->query($updateRate);
    			
			$ret['success'] = true;
			$ret['id'] = $id;
			$ret['rating_count'] = (integer) $p['rating_count'] + $rating;
			$ret['rating'] = $p['rating'] + 1;
			$ret['average'] = $ret['rating_count']/$ret['rating'];
			
			$this->_helper->json->sendJson($ret);
		}
	}
	
	public function updatePlaceNameAction()
	{
		$id = $this->_request->getParam('id'); 
		$newPlaceName = $this->_request->getParam('name');
    	
		if ($this->_request->isXmlHttpRequest())
		{
		    $db = $this->db;
		    $ret = array();
			
		    $sql = "UPDATE places SET name=".$db->quote($newPlaceName, 'STRING') ." WHERE id=".$db->quote($id, 'INTEGER') ;
		    try {
	           	$db->query($sql);
			    $ret['success'] = true;
		    }
		    catch (Exception $e)
		    {
		    	$ret['success'] = false;
		    }
		    $ret['name'] = $newPlaceName;
			$this->_helper->json->sendJson($ret);
		}
	}	
	public function autocompleteAction()
	{
		$data = $this->_request->getParams();
		if ($this->_request->isXmlHttpRequest())
		{
			// check the parameter
			if(isset($_GET['part']) and $_GET['part'] != '')
			{	
				$part = VN_unaccent(strtolower($_GET['part']));
				$ret = $this->m->searchBelongTo($data, $part);
				Zend_Registry::get('logger')->log("Autocomplete return:" . $ret, Zend_Log::INFO);
		        $parts = explode (' ',$part);
				$results = array();
				$ids = array();
				foreach($ret as $k => $v)
				{
					$items = array($v['unaccented_name'] => $v['name'] );
					$ids = $v['id'];
					foreach ($items as $key => $value) 
			 		{
			 			$matched = true;
		                $lower_key = strtolower($key);
		                foreach ($parts as $p)
		                {
		                    if (strpos($lower_key, $p) === false) 
		                       $matched = false; break;
		                }
		               	if ($matched)
		               	{
							$results[] = array('id' => $ids, 'name' => $value);
		               	}
			 		}
				}
			}
			$this->_helper->json->sendJson($results);
		}
	}
}
?>
